package com.my.okhttps.test.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ejlchina.okhttps.HttpResult;
import com.ejlchina.okhttps.OkHttps;
import com.my.core.domain.exception.ServiceException;
import com.my.okhttps.test.service.ISheBao2Service;
import com.my.okhttps.test.vo.shebao2.*;
import com.my.okhttps.utils.XmlUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author timo 2021/3/3
 */
@Component
@Slf4j
public class Shebao2ServiceImpl implements ISheBao2Service {
    /**社保标签*/
    public static final String SHEBAO_TAR2 = "SHE_BAO2";
    public static final String BASE = "/yhbcp-engine/rest/callBusiness";
    public static final String URL_BASE = "/yhbcp-engine/rest/";
    /**社会保障卡信息查询*/
    public static final String get_card_info = "WZ1000";
    /**社会保障卡激活*/
    public static final String activate = "WZ7000";
    /**社保卡挂失、解挂、冻结*/
    public static final String other_operation = "G400";
    /**社会保障卡参保关系转移*/
    public static final String relation_transfer = "ZY1000";
    /** 就业外出务工地查询 */
    public static final String go_out_work_place_query = "INT_Q_JY_001";
    /** 惠民惠农一卡通支付明细  */
    public static final String ecard_query = "INT_Ecard_005";

    /**接口基础域名地址*/
    public static String DOMAIN;
    /**加密key*/
    public static String publicKeyStr;

    @Value("${shebao2.domain:}")
    public void setDOMAIN(String DOMAIN) {Shebao2ServiceImpl.DOMAIN = DOMAIN;
    }
    @Value("${shebao2.publicKeyStr:}")
    public void setPublicKeyStr(String publicKeyStr) {
        Shebao2ServiceImpl.publicKeyStr = publicKeyStr;
    }

    public JSONObject operation(String xmlStr,String url){
        HttpResult httpResult = OkHttps.sync(url)
                .bodyType(OkHttps.XML)
                .addUrlPara("biz_content", xmlStr)
                .addHeader("publicKeyStr", publicKeyStr)
                .skipSerialPreproc()
                .tag(SHEBAO_TAR2)
                .post();
        HttpResult.Body body = httpResult.getBody();
        JSONObject jsonObject = JSON.parseObject(String.valueOf(body));
        String code = jsonObject.getString("code");
        if("1".equals(code)) {
            JSONObject biz_data = jsonObject.getJSONObject("biz_data");
            code = biz_data.getString("code");
            if("1".equals(code)){
                return biz_data;
            }
            if("-1".equals(code)){
                String message = biz_data.getString("message");
                throw new ServiceException(message);
            }
            if("200".equals(code)){
                return biz_data;
            }
            //200
            return biz_data;
        }
        throw new ServiceException(jsonObject.toJSONString());
    }

    /**
     * {"msg":"成功","code":"1","sub_msg":"","sub_code":"","biz_data":{"output":{"recordcount":"1","resultset":[{"aae010":"6217212304000203566","aff002":null,"aac067":null,"aac002":"510502193506031124","aab034":"510500","aaz502":"正常","aaz702":"可代扣代发","aaz503":"20130601","aaz500":"A10241505","aac080":"102","yhkh":"6217212304000203566","aae007":"510901","aac006":"19350603","aac003":"刘开英","aac058":"01","aae006":"泸州北方","aac004":"2","aae005":null,"aac147":"510502193506031124","aab301_310":"510500"}]},"code":"1","message":null}}
     * @param inputXml
     * @return
     */
    @Override
    public SheBaoBaseInfo getCardInfo(InputXml inputXml){
        inputXml.setJybh(get_card_info);
        String xmlStrTo = XmlUtils.objectToXmlStr(inputXml, InputXml.class);

        JSONObject data = operation(xmlStrTo,DOMAIN+BASE);
        data = data.getJSONObject("output");
        Integer recordcount = data.getInteger("recordcount");
        if(recordcount>0){
            JSONArray resultset = data.getJSONArray("resultset");
            JSONObject o = (JSONObject) resultset.get(0);
            SheBaoBaseInfoVo sheBaoBaseInfoVo = JSON.parseObject(o.toJSONString(), SheBaoBaseInfoVo.class);
            return new SheBaoBaseInfo(sheBaoBaseInfoVo);
        }
        throw new ServiceException(data.toJSONString());
    }

    @Override
    public String activate(InputXml inputXml) {
        SheBaoBaseInfo cardInfo = getCardInfo(inputXml);
        inputXml.setCardNo(cardInfo.getShebaoCard());
        inputXml.setAreaNo(cardInfo.getAreaNo());
        inputXml.setUserName(cardInfo.getUserName());
        inputXml.setJybh(activate);
        inputXml.buildAct(inputXml);
        String xmlStrTo = XmlUtils.objectToXmlStr(inputXml, InputXml.class);
        operation(xmlStrTo,DOMAIN+BASE);
        //激活只有状态码,这里没抛出异常,证明状态码为1 标识激活成功
        return "激活成功";
    }

    @Override
    public String otherOperation(InputXml inputXml) {
        SheBaoBaseInfo cardInfo = getCardInfo(inputXml);
        inputXml.setAreaNo(cardInfo.getAreaNo());
        inputXml.setUserName(cardInfo.getUserName());
        inputXml.setJybh(other_operation);
        inputXml.buildOtherOperation(inputXml);

        String xmlStrTo = XmlUtils.objectToXmlStr(inputXml, InputXml.class);
        operation(xmlStrTo,DOMAIN+BASE);
        return "操作成功";
    }

    @Override
    public String relationTransfer(InputXml inputXml) {
        SheBaoBaseInfo cardInfo = getCardInfo(inputXml);
        inputXml.setCardNo(cardInfo.getShebaoCard());
        inputXml.setUserName(cardInfo.getUserName());
        inputXml.setAreaNo(cardInfo.getAreaNo());
        inputXml.setJybh(relation_transfer);
        inputXml.buildRelationTransfer(inputXml);
        String xmlStrTo = XmlUtils.objectToXmlStr(inputXml, InputXml.class);
        operation(xmlStrTo,DOMAIN+BASE);
        return "操作成功";
    }

    @Override
    public  List<GoOutWorkPlaceVo> goOutWorkPlaceQuery(InputXml inputXml) {
        inputXml.setJybh(go_out_work_place_query);
        String xmlStrTo = XmlUtils.objectToXmlStr(inputXml, InputXml.class);
        JSONObject operation = operation(xmlStrTo, DOMAIN + URL_BASE + go_out_work_place_query);
        JSONArray rows = operation.getJSONArray("rows");
        Iterator<Object> iterator = rows.iterator();


        List<GoOutWorkPlaceVo> returnVos = new ArrayList<GoOutWorkPlaceVo>();
        while (iterator.hasNext()) {
            JSONObject next = (JSONObject) iterator.next();
            String aae036 = next.getString("aae036");
            String ycc0o4 = next.getString("ycc0o4");
            String aac003 = next.getString("aac003");

            GoOutWorkPlaceVo goOutWorkPlaceVo = new GoOutWorkPlaceVo(aac003,ycc0o4,aae036);
            returnVos.add(goOutWorkPlaceVo);
        }
        return returnVos;
    }

    @Override
    public List<EcardPayDetail>  ecardQuery(InputXml inputXml) {
        inputXml.setJybh(ecard_query);
        String xmlStrTo = XmlUtils.objectToXmlStr(inputXml, InputXml.class);
        JSONObject operation = operation(xmlStrTo, DOMAIN + URL_BASE + ecard_query);
        JSONArray result = operation.getJSONArray("result");

        Iterator<Object> iterator = result.iterator();
        List<EcardPayDetail> returnVos = new ArrayList<EcardPayDetail>();
        while (iterator.hasNext()) {
            JSONObject next = (JSONObject) iterator.next();
            String projectName = next.getString("projectName");
            String aac003 = next.getString("aac003");
            String amt = next.getString("amt");
            String period = next.getString("period");
            String grantTime = next.getString("grantTime");
            String aac002 = next.getString("aac002");

            String format = DateUtil.formatDateTime(DateUtil.parseDateTime(grantTime));

            EcardPayDetail ecardPayDetail = new EcardPayDetail(aac003,aac002,projectName,amt,format,period);
            returnVos.add(ecardPayDetail);
        }
        return returnVos;
    }
}
